import React, { Component } from 'react'
import {Redirect, Route,Switch} from 'react-router-dom'
import {adminRoutes} from '../../router'
import { Layout,Row,Col } from 'antd';
import SideBar from './SideBar'
import DropMenu from './DropMenu'
import './index.css'
import {
  MenuUnfoldOutlined,
  MenuFoldOutlined
} from '@ant-design/icons';
import {connect} from 'react-redux'
const { Header, Sider, Content } = Layout;

class Main extends Component {
  state = {
    collapsed: false,
    filterRoutes:[]  //处理后的单层路由数据包
  };

  toggle = () => {
    this.setState({
      collapsed: !this.state.collapsed,
    });
  };

  componentDidMount(){
    let filterRoutes = [];  //临时存储过滤的数据
    adminRoutes.forEach((item)=>{
      if(item.children){
        filterRoutes = [...filterRoutes,...item.children]
      }else{
        filterRoutes.push(item)
      }
    })
    this.setState({filterRoutes})
  }

  render() {
    let {role} = this.props.userReducer.userInfo  //提取当前用户的角色值
    return (
      <Layout>
        <Sider trigger={null} collapsible collapsed={this.state.collapsed}>
          <div className="logo" />
          {/* 侧边菜单栏组件 */}
          <SideBar/>
        </Sider>
        <Layout className="site-layout">
          <Header className="site-layout-background" style={{ padding: 0 }}>
            <Row>
              <Col>
                {React.createElement(this.state.collapsed ? MenuUnfoldOutlined : MenuFoldOutlined, {
                  className: 'trigger',
                  onClick: this.toggle,
                })}
              </Col>
              <Col offset={18}>
                <DropMenu/>
              </Col>
            </Row>
            
          </Header>
          <Content
            className="site-layout-background"
            style={{
              margin: '24px 16px',
              padding: 24,
              minHeight: 280,
            }}
          >
            <Switch>
              {
                this.state.filterRoutes.map((item, index) => {
                  let bool = item.roles.includes(role)
                  return bool ? <Route {...item} key={index} /> : ''
                })
              }
              <Redirect from='*' to="/admin/404"/>
            </Switch>

          </Content>
        </Layout>
      </Layout>
    );
  }
}
const mapStateToProps = (state)=>{
  return state
}
export default connect(mapStateToProps)(Main)
